<?php

namespace App\Services\Traits;

use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Validator;
/**
 * 
 */
trait UploadImageTrait
{
    
    public function upload(Request $request)
    {
        $validator = Validator::make($request->all(),[
            $this->check_field => [
                'required', 
                'image', 
                'max:1024'

            ]
            ],[
                $this->check_field.'.required' => '长传不能为空',
                $this->check_field.'.image' => '图片类型为jpeg, png, bmp, gif, 或 svg',
                $this->check_field.'.max' => '图片最大为1M',
            ]);
        if($validator->fails()){
            return response()->json(['code' => 400, 'msg' => 'error', 'data' => $validator->errors()->all()]); 
        }else{
            $path = $this->path.date("Ym", time()).'/' . date("d", time());
            $url = Storage::url(Storage::disk('public')->put($path, $request->{$this->check_field})); 
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => ['url' => $url, 'host' => env('APP_URL', is_https().$request->server('HTTP_HOST'))]]); 
        }
    }

}
